<template>
  <!-- 按机构选择相机 -->
  <div class="imColumn common-tree-select-jkasdjfklasjdkfljaskdlfj"
    style="margin-right:10px;border: 1px solid #f5f7fa;padding:6px;height:100%!important" v-loading="loading">
    <div class="head-container">
      <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
        style="margin-bottom: 20px" @keyup.enter.native="searchEnter" />
    </div>
    <div class="imscrollo">
      <el-tree :render-content="renderContent" :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
        node-key="camId" :filter-node-method="filterNode" draggable :allow-drag="allowDrag" :allow-drop="allowDrop"
        @node-drag-start="handleDragStart" @node-drag-enter="handleDragEnter" @node-drag-leave="handleDragLeave"
        @node-drag-over="handleDragOver" @node-drag-end="handleDragEnd" @node-drop="handleDrop" ref="tree"
        @node-click="handleNodeClick" />
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { treeCameraData } from "./map/api";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import EventBus from '@/utils/eventBus'
import util from '@/libs/util'

export default {
  name: "common-org-camera-select",
  props: {
    sourceData: Array,
    clickRepeatable: Number, // 0 重复点击不再表示全选 1 点击 取消点击（全选）
    allClickable: Number, // 0 只可点击相机 1 全部可点击
    errorStart: Object,
  },

  components: {},

  data() {
    return {
      qiangjiPic: require('@/assets/images/qiangji-normal.png'),
      qiujiPic: require('@/assets/images/qiuji-normal.png'),
      stime: null,
      loading: false,
      queryParams: {
        deptId: ''
      },
      deptName: undefined, // 机构名称
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      // ownListData: {},
      // ownListNode: {}
    };
  },

  created() {
    this.getTreeselect();
  },


  mounted() {
    // 解决el-tootip快速滑动 页面右侧滚动条抖动
    document.querySelector('body').setAttribute('style', 'overflow:hidden;!important')
  },

  beforeDestroy() {
    // 解决el-tootip快速滑动 页面右侧滚动条抖动 去除css
    document.querySelector('body').removeAttribute('style', 'overflow:hidden;!important')
  },

  activated: function () {

  },

  methods: {

    /**
     * 按回车直接搜索
     */
    searchEnter(e) {
      if (this.stime != null) {
        clearTimeout(this.stime)
      }

      var keycode = window.event ? e.keyCode : e.which
      if (keycode == 13) {
        this.$refs.tree.filter(this.deptName)
      }
    },

    handleDragStart(node, ev) {
      console.log('drag start', node)

      // 传输数据
      EventBus.$emit('dragStart',
        {
          result: node.data
        })
    },

    handleDragEnter(draggingNode, dropNode, ev) {
      console.log('tree drag enter: ', dropNode.label);
    },

    handleDragLeave(draggingNode, dropNode, ev) {
      console.log('tree drag leave: ', dropNode.label);
    },

    handleDragOver(draggingNode, dropNode, ev) {
      console.log('tree drag over: ', dropNode.label);
    },

    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      console.log('tree drag end: ', dropNode && dropNode.label, dropType);
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('tree drop: ', dropNode.label, dropType);
    },

    /**
     * 目标节点能否被放置。
     * type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后。
     */
    allowDrop(draggingNode, dropNode, type) {
      return false
    },

    /**
     * 是否可拖拽
     */
    allowDrag(draggingNode) {
      return draggingNode.data.camId != null && draggingNode.data.camId != undefined && draggingNode.data.camId !== ''
    },

    // 解决树结点过长的问题
    ellipsis(value, len) {
      if (!value) return "";
      if (value.length > len) {
        return value.slice(0, len) + "...";
      }
      return value;
    },

    /**
     * 树结构渲染
     */
    renderContent(h, { node, data, store }) {
      let nodeClassName
      nodeClassName = 'org-tree' // 山高图标

      if (data != null && data != undefined && util.isNotEmpty(data.camId)) {
        if (util.isNotEmpty(data.ptzCtrl) && data.ptzCtrl == '0') {
          nodeClassName = 'org-qiuji-online'
        } else {
          nodeClassName = 'org-qiangji-online'
        }
      }

      if (((this.queryParams.deptId == data.id && data.id != null) || (this.queryParams.deptId == data.camId && data.camId != null))) {
        return (
          // <svg-icon icon-class={camType} /> 原来在第二行 <el-tooltip content={node.label} placement="right">
          <span style="font-size:14px;cursor:pointer;color:#06A2FE;font-weight:bold">
            <svg-icon
              class-name={nodeClassName}
              icon-class={nodeClassName}
            />

            <el-tooltip content={node.label} placement="right">
              <span style="padding-left:2px;">
                {this.ellipsis(node.label, 10)}
              </span>
            </el-tooltip>
          </span>
        );
      } else {
        return (
          // <svg-icon class-name={nodeClassName} icon-class={nodeClassName} /> 原来在第二行
          <span style="font-size:14px;cursor:pointer;">
            <svg-icon
              class-name={nodeClassName}
              icon-class={nodeClassName}
            />
            <el-tooltip content={node.label} placement="top" open-delay={300}>
              <span style="padding-left:2px;">
                {this.ellipsis(node.label, 10)}
              </span>
            </el-tooltip>
          </span>
        );
      }
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      this.loading = true
      treeCameraData().then((response) => {
        this.loading = false
        this.deptOptions = response.data;
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },

    // 筛选节点
    // filterNode(value, data) {
    //   if (!value) return true;
    //   return data.label.indexOf(value) !== -1;
    // },

    // 筛选节点
    filterNode(value, data, node) {
      if (!value) return true
      let parentNode = node.parent, labels = [node.label], level = 1
      while (level < node.level) {
        labels = [...labels, parentNode.label]
        parentNode = parentNode.parent
        level++
      }
      return labels.some(label => label.indexOf(value) !== -1)
    },

    /**
     * 设置deptId
     */
    setId(val) {
      console.log(val)
      if (val != null && val != undefined) {
        if (val['id'] != null && val['id'] != undefined && val['id'] != -1) {
          return val['id']
        } else {
          return val['camId']
        }
      }
    },

    // 节点单击事件
    handleNodeClick(data, node, obj) {
      // console.log(data, node, obj)
      // this.ownListData = data
      // this.ownListNode = node
      // 提交数据 只有点击相机才提交数据
      if (data != null && data != undefined) {
        var id = this.queryParams.deptId
        // console.log(id)
        // 区分是否都可点击 0 只可点击相机 1 全部可点击
        if (this.allClickable == 1) {
          if (this.clickRepeatable != 0) {
            // 再次点击表示取消全选
            if (id == this.setId(data)) {
              // 取消选中
              this.queryParams.deptId = null
              this.$emit('orgClick', null)
              // eventBus
              EventBus.$emit('cameraSelected', null)
            } else {

              this.queryParams.deptId = this.setId(data)
              this.$nextTick(() => {
                // 选中
                this.$emit('orgClick', data)
                // eventBus
                EventBus.$emit('cameraSelected', data)
              })

            }
          } else {
            this.$emit('orgClick', data)
          }
        } else {

          if (data.camId != null && data.camId != undefined) {

            if (id == data.camId && this.clickRepeatable != 0) {
              // 取消选中
              this.queryParams.deptId = null
              this.$emit('orgClick', null)
              // eventBus
              EventBus.$emit('cameraSelected', null)
            } else {
              this.queryParams.deptId = data.camId
              this.$nextTick(() => {
                // 选中
                var da = data
                da['deptName'] = node['parent']['data']['label']
                this.$emit('orgClick', da)
                // eventBus
                EventBus.$emit('cameraSelected', da)
              })

            }
          }
        }
      }
    }
  },


  watch: {
    // errorStart: {
      // handler(val) {
        // if (val.getList) {
          // this.$nextTick(() => {
            // console.log(this.$refs.tree.getNode(val.camId))
            // var data = this.$refs.tree.getNode(val.camId).data
            // if (data.camId != null && data.camId != undefined) {
            //   console.log(data.camId)
            //   console.log(666666666666666)
            //   this.queryParams.deptId = data.camId
            //   // 选中
            //   setTimeout(() => {
            //     var da = data
            //     this.$emit('orgClick', da)
            //     // eventBus
            //     EventBus.$emit('cameraSelected', da)
            //   },100)
            // }
          // })

          // var data = this.ownListData
          // var node = this.ownListNode
          // // var id = this.queryParams.deptId
          // this.handleNodeClick(data, node)

        // }
      // },
      // deep: true,
      // immediate: true
    // },
    sourceData: {
      handler(val, oldVal) {

      },
      deep: true,
      immediate: true,
    },

    /**
     * 机构名称
     */
    deptName: {
      handler(val, oldVal) {

        // if (val == null || val == undefined || val === '') {
        //   this.$emit('orgClick', null)
        // }

        if (this.stime != null) {
          clearTimeout(this.stime)
        }

        if (val != null && val != undefined) {
          this.stime = setTimeout(() => {
            this.$refs.tree.filter(val)
          }, 2000);
        }
      },
      deep: true,
      immediate: true,
    },

    domWidth(val, oldVal) { },
  },
};
</script>


<style lang="scss">
.common-tree-select-jkasdjfklasjdkfljaskdlfj {
  min-height: calc(100vh - 106px);

  .el-tree-node__content:hover {
    // #B0C4DE
    background-color: #f5fcf7 !important;
  }

  .el-tree {
    height: calc(100vh - 200px) !important;
    width: 14vw !important;
  }

  .org-tree {
    background: url(~@/assets/image/map-img/tree-org.png) center no-repeat;
  }

  .org-road {
    background: url(~@/assets/image/map-img/tree-road.png) center no-repeat;
  }

  .org-qiangji-online {
    background: url(~@/assets/image/map-img/qiangji-normal.png) center no-repeat;
  }

  .org-qiangji-breakdown {
    background: url(~@/assets/image/map-img/qiangji-breakdown.png) center no-repeat;
  }

  .org-qiangji-offline {
    background: url(~@/assets/image/map-img/qiangji-offline.png) center no-repeat;
  }

  .org-qiuji-online {
    background: url(~@/assets/image/map-img/qiuji-normal.png) center no-repeat;
  }

  .org-qiuji-breakdown {
    background: url(~@/assets/image/map-img/qiuji-breakdown.png) center no-repeat;
  }

  .org-qiuji-offline {
    background: url(~@/assets/image/map-img/qiuji-offline.png) center;
  }
}
</style>